'''
@create_time: 2025/10/17 下午2:46
@Author: GeChao
@File: loginbusiness.py
'''
from playwright.async_api import Page
from page.login.login_page import LoginPage
from tools.log import Logger
from tools.general_tool import ReadConf
from pathlib import Path

logger = Logger().logger


class LoginBusiness(LoginPage):
    def __init__(self, page: Page):
        super().__init__(page)
        # 读取环境配置
        self.env_config = self._load_env_config()
    
    def _load_env_config(self):
        """加载环境配置"""
        try:
            conf_path = Path(__file__).resolve().parents[4] / 'conf' / 'env_config.ini'
            if conf_path.exists():
                readconf = ReadConf(conf_path)
                return readconf
            else:
                logger.warning("环境配置文件不存在，使用默认配置")
                return None
        except Exception as e:
            logger.error(f"加载环境配置失败: {e}")
            return None
    
    def _get_login_url(self):
        """获取登录URL"""
        # 优先检查环境变量（用于Jenkins）
        import os
        env_override = os.getenv('TEST_ENV')
        if env_override:
            if env_override == 'intranet':
                return os.getenv('INTRANET_LOGIN_URL', 'http://localhost:8443/login')
            elif env_override == 'local':
                return os.getenv('LOCAL_LOGIN_URL', 'http://localhost:3000/login')
        
        # 然后检查配置文件
        if self.env_config:
            try:
                env = self.env_config.get_conf('ENVIRONMENT').get('env', 'qa4')
                if env == 'intranet':
                    return self.env_config.get_conf('INTRANET').get('login_url')
                elif env == 'local':
                    return self.env_config.get_conf('LOCAL').get('login_url')
                else:
                    return self.env_config.get_conf('QA4').get('login_url')
            except:
                pass
        # 默认返回QA4环境
        return "https://qa4-wms.yqn.com/login"

    def _get_login_credentials(self):
        """获取登录凭据"""
        # 优先检查环境变量（用于Jenkins）
        import os
        env_override = os.getenv('TEST_ENV')
        if env_override == 'intranet':
            env_username = os.getenv('INTRANET_USERNAME')
            env_password = os.getenv('INTRANET_PASSWORD')
            if env_username and env_password:
                return env_username, env_password
        
        # 然后检查配置文件
        if self.env_config:
            try:
                env = self.env_config.get_conf('ENVIRONMENT').get('env', 'qa4')
                if env == 'intranet':
                    intranet_config = self.env_config.get_conf('INTRANET_LOGIN')
                    return intranet_config.get('username'), intranet_config.get('password')
            except:
                pass
        return None, None

    async def login(self, email: str = None, password: str = None):
        """执行登录操作"""
        try:
            # 如果没有提供凭据，尝试从配置文件获取
            if not email or not password:
                config_email, config_password = self._get_login_credentials()
                email = email or config_email or "gechao@yqn.com"
                password = password or config_password or "123456"
            
            login_url = self._get_login_url()
            logger.info(f"开始访问登录页: {login_url}")
            logger.info(f"使用账号: {email}")
            await self.page.goto(login_url, wait_until="networkidle")
            logger.info("✅ 登录页加载完成")
            
            # 等待页面完全渲染
            await self.page.wait_for_timeout(4000)
            email_locator = self.page.locator('input[type="text"]')
            password_locator = self.page.locator('input[type="password"]')
            await email_locator.fill(email)
            await password_locator.fill(password)
            login_btn_locator = self.page.locator('button:has-text("登录")')
            await login_btn_locator.click()
            # 等待登录完成 - 直接等待跳转到home页面
            try:
                # 等待URL包含"/home"
                await self.page.wait_for_url("**/home", timeout=15000)
                logger.info(f"✅ 登录成功,当前URL: {self.page.url}")
                # 等待网络空闲
                await self.page.wait_for_load_state("networkidle", timeout=10000)
                logger.info("✅ 页面加载完成")
            except Exception as e:
                # 检查是否已经在home页面了
                current_url = self.page.url
                if "/home" in current_url or "login" not in current_url:
                    logger.info(f"✅ 登录已成功(已在首页),URL: {current_url}")
                    return
                logger.error(f"❌ 等待页面跳转失败: {e}")
                logger.error(f"当前URL: {current_url}")
                await self.page.screenshot(path="login_failed.png")
                raise Exception(f"登录失败,请检查账号密码: {e}")
        except Exception as e:
            # 如果已经在home页面,认为登录成功
            current_url = self.page.url
            if "/home" in current_url:
                logger.info(f"✅ 登录成功(已跳转到首页),URL: {current_url}")
                return
            logger.error(f"❌ 登录过程发生错误: {e}")
            logger.error(f"当前URL: {current_url}")
            await self.page.screenshot(path="login_error.png")
            raise

    async def switch_warehouse(self, from_warehouse: str, to_warehouse: str):
        """切换仓库 - 业务逻辑"""
        try:
            element = await self.warehouse_button(role="button", name=from_warehouse)
            await element.click(timeout=5000)
        except Exception as e:
            logger.warning(f"点击仓库按钮失败: {e}, 尝试使用 text 定位")
            element = await self.warehouse_option(text=from_warehouse, exact=True)
            await element.click()
        await self.page.locator(".ant-menu").get_by_role(
            "menuitem", name=to_warehouse
        ).click()
